/*
 * This is made for the edit profile picture form, it changes the profile picture of a member
 */
package controllers.classes;

import classes.HibernateUtil;
import dao.EmployeeDao;
import dao.StudentDao;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Employee;
import models.Student;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Achie
 */
public class EditProfilePictureController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String fileName = null;
        String url; //the url of the (to be uploaded) file
        String path = "/uploads/profilepictures"; //the path where the profile picture will go to

        //-----------------------------------------------------
        //Process the encoded form & save the file on the uploads folder
        //-----------------------------------------------------
        String folderLocation = request.getRealPath(path); //get the exact folder location
        HashMap<String, String> formParams = new HashMap<String, String>();

        // Check that we have a file upload request
        FileItem i = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if (isMultipart) {

                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request
                List<FileItem> items = upload.parseRequest(request);

                // Process the uploaded items
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        // Process a regular form field
                        formParams.put(item.getFieldName(), item.getString());
                        // fileName = request.getParameter("filename");
                    } else {
                        // Process a file upload
                        fileName = item.getName();
                        File uploadedFile = new File(folderLocation + File.separator + fileName);
                        item.write(uploadedFile); //write the file on the server
                        i = item;
                    }
                }
            }

            url = path + "/" + fileName;
            long memberid = Long.parseLong(formParams.get("id"));

            HibernateUtil hu = new HibernateUtil();
            EmployeeDao ed = new EmployeeDao(hu.openSession());
            StudentDao sd = new StudentDao(hu.openSession());
            Employee emp = ed.get(memberid);
            if (emp != null) { //if true, it's an employee
                emp.setProfileurl(url);

                if (i.getSize() > 3145728) { //if bigger than 3 mb, redirect
                    response.sendRedirect("jsp/edit_profile_picture.jsp");
                } else {

                    if (url.endsWith("jpeg") || url.endsWith("png") || url.endsWith("jpg")) { //supported extensions
                        ed.update(emp); //update employee object with new picture
                        response.sendRedirect("userProfile?id=" + memberid);
                    } else {
                        response.sendRedirect("jsp/edit_profile_picture.jsp"); //redirect (error)
                    }
                }

            } else { //its a student
                Student st = sd.get(memberid);
                st.setProfileurl(url);

                if (i.getSize() > 3145728) { //if bigger than 3 mb
                    response.sendRedirect("jsp/edit_profile_picture.jsp");
                } else {

                    if (url.endsWith("jpeg") || url.endsWith("png") || url.endsWith("jpg")) { //supported extension
                        sd.update(st); //update the student object with the new picture
                        response.sendRedirect("userProfile?id=" + memberid);
                    } else {
                        response.sendRedirect("jsp/edit_profile_picture.jsp"); //redirect (error)
                    }
                }
            }
            //response.sendRedirect("userProfile?id=" + memberid);
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            throw new ServletException(fue.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
